package io.framework.modules.station.controller;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.framework.common.annotation.LogOperation;
import io.framework.common.constant.Constant;
import io.framework.common.exception.ErrorCode;
import io.framework.common.page.PageData;
import io.framework.common.utils.ExcelUtils;
import io.framework.common.utils.Result;
import io.framework.common.validator.AssertUtils;
import io.framework.common.validator.ValidatorUtils;
import io.framework.common.validator.group.AddGroup;
import io.framework.common.validator.group.DefaultGroup;
import io.framework.common.validator.group.UpdateGroup;
import io.framework.modules.air.dto.AirDTO;
import io.framework.modules.air.service.AirService;
import io.framework.modules.station.dto.StationDTO;
import io.framework.modules.station.excel.StationExcel;
import io.framework.modules.station.service.StationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 站点数据
 *
 * @author Gujq email
 * @since 1.0.0 2020-05-20
 */
@RestController
@Api(tags = "站点数据")
public class StationController {
    @Autowired
    private StationService stationService;

    @Autowired
    private AirService airService;

    @GetMapping("station/station/page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String")
    })
    @RequiresPermissions("sys:station:page")
    public Result<PageData<StationDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {

        PageData<StationDTO> page = stationService.pages(params);

        return new Result<PageData<StationDTO>>().ok(page);
    }

    @GetMapping("station/station/getStationInfoByParams")
    @ApiOperation("根据条件获取站点信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "站点名称", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "type", value = "1-空气 2-水 3-土壤 4-噪声", paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "control", value = "空气：1-国控 2-全市 3-省控  水： 1-地表水 2-城镇内河 3-重点治理城镇内河 4-引用水源地 5-海洋浮标点 噪声 ：1-道路交通噪声 2-区域环境噪声 3-功能区噪声", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "xmin", value = "最小经度", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "xmax", value = "最大经度", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "ymin", value = "最小纬度", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "ymax", value = "最大纬度", paramType = "query", dataType = "String"),
    })
    public Result<List<StationDTO>> getStationInfoByParams(@ApiIgnore @RequestParam Map<String, Object> params) {

        List<StationDTO> list = stationService.getStationInfoByParams(params);
        list.forEach(v -> {
            if (v.getType() == 1) {
                //空气
                Map<String, Object> map = new HashMap<>();
                map.put("stationId", v.getId());
                map.put("type", v.getType());
                AirDTO airDTO = airService.getAirDTOIOnfoByParam(map);
                if (airDTO != null) {
                    v.setLevel(airDTO.getLevel());
                    v.setClassify(airDTO.getClassify());
                }
            }
        });
        return new Result<List<StationDTO>>().ok(list);
    }

    @GetMapping("station/station/{id}")
    @ApiOperation("信息")
    public Result<StationDTO> get(@PathVariable("id") Long id) {
        StationDTO data = stationService.get(id);

        return new Result<StationDTO>().ok(data);
    }

    @PostMapping("station/station/save")
    @ApiOperation("保存")
    @LogOperation("添加站点信息")
    @RequiresPermissions("sys:station:save")
    public Result save(StationDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        //判断编码是否存在
        if(checkStationCode(dto)){
            return new Result().error(ErrorCode.ALREADY_EXIST_CODE);
        }

        stationService.save(dto);

        return new Result();
    }

    /**
     * 判断编码是否存在
     * @param dto
     * @return
     */
    private Boolean checkStationCode(StationDTO dto){
        Boolean flag = false;
        if(StringUtils.isNotBlank(dto.getCode())){
            Map<String,Object> map = new HashMap<>();
            map.put("code",dto.getCode());
            List<StationDTO> list = stationService.getStationInfoByParams(map);
            if(CollectionUtils.isNotEmpty(list)){
                flag = true;
            }
        }
        return flag;
    }

    @PutMapping("station/station/update")
    @ApiOperation("修改")
    @LogOperation("修改站点信息")
    @RequiresPermissions("sys:station:update")
    public Result update(StationDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        //判断编码是否存在
        if(checkStationCode(dto)){
            return new Result().error(ErrorCode.ALREADY_EXIST_CODE);
        }

        stationService.update(dto);

        return new Result();
    }

    @DeleteMapping("station/station/delete/{id}")
    @ApiOperation("删除")
    @LogOperation("删除站点信息")
    @RequiresPermissions("sys:station:delete")
    public Result delete(@PathVariable("id") String id) {
        //效验数据
        AssertUtils.isBlank("id", ErrorCode.IDENTIFIER_NOT_NULL);

        stationService.deleteById(id);

        return new Result();
    }

}